package test.test01;

import java.util.PriorityQueue;

public class MyTimer {
    private static PriorityQueue<MyTask> queue = new PriorityQueue<>();
    private static Object locker = new Object();
    public void schedule(MyTask task){
        synchronized(locker){
            queue.offer(task);
            locker.notify();
        }
    }
    public static void main(String[] args) {
        t.start();
        MyTimer timer = new MyTimer(); 
        MyTask myTask = new MyTask(new Runnable(){
            @Override
            public void run(){
                System.out.println("定时器执行任务 1");
            }
        },3000);
        timer.schedule(myTask);
    }

    private static Thread t = new Thread(()->{
        while(true){    
            synchronized(locker) {
                try{
                    while(queue.isEmpty()){
                        locker.wait();
                    }
                    MyTask task = queue.peek();
                    long now = System.currentTimeMillis();
                    if(now >= task.time){
                        queue.poll();
                        task.runnable.run();
                    }else{
                        locker.wait(task.time - now);
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    });
}
class MyTask implements Comparable<MyTask>{
    public Runnable runnable;
    public long time;

    public MyTask(Runnable runnable,long time){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }
    @Override
    public int compareTo(MyTask o){
        return (int)(this.time - o.time);
    }
}


   

